import { useEffect, useRef, useState } from "react"

import sidepanelStyle from "../style/sidepanel.module.css"

function IndexSidePanel() {
  const [data, setData] = useState(["请输入问题"])
  const dataRef = useRef(["请输入问题"])
  const [inputValue, setInputValue] = useState("")
  const urlRef = useRef()
  const content = useRef(null)
  const { textarea, color, button, question, answer, contentBox } =
    sidepanelStyle

  useEffect(() => {
    content.current.scrollTop = content.current.scrollHeight
    dataRef.current = data
  }, [data])
  useEffect(() => {
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      console.log(message, "message")

      if (message.type === "selectText") {
        setInputValue(message.data)
      } else if (message.type === "allHtml") {
        setInputValue(message.data)
      } else if (message.type === "changeTab") {
        changeTab(message.data)
      } else if (message.type === "loginSuccess") {
        loginSuccess(message.data)
      }
    })
  }, [])

  function loginSuccess(data) {
    console.log(data)
  }

  function changeTab(originUrl) {
    if (!urlRef.current) {
      urlRef.current = originUrl
      chrome.storage.local.get().then((result) => {
        if (result[originUrl]) {
          setData(result[originUrl] || [])
        } else {
          setData(["请输入问题"])
        }
        urlRef.current = originUrl
      })
    } else {
      chrome.storage.local
        .set({ [urlRef.current]: dataRef.current })
        .then(() => {
          chrome.storage.local.get().then((result) => {
            if (result[originUrl]) {
              setData(result[originUrl] || [])
            } else {
              setData(["请输入问题"])
            }
            urlRef.current = originUrl
          })
        })
    }
  }

  function submit() {
    setData((old) => {
      demo(urlRef.current, [...old, inputValue])
      return [...old, inputValue]
    })
    setInputValue("")
  }

  function demo(url, arr) {
    setTimeout(() => {
      if (url !== urlRef.current) {
        console.log("页面已经变更")
        console.log(arr)

        chrome.storage.local
          .set({ [url]: [...arr, "我是偷偷更新的"] })
          .then(() => {
            console.log("我偷偷更新了", arr)
          })
        return
      }
      setData((old) => {
        return [...old, "我不知道a"]
      })
    }, 5000)
  }

  function textareaChange(e) {
    setInputValue(e.target.value)
  }
  function getContent() {
    return data.map((item, index) => {
      if (index % 2 === 0) {
        return (
          <div key={index} style={{ marginBottom: "30px" }}>
            <div className={answer}>{item}</div>
          </div>
        )
      }
      return (
        <div
          key={index}
          style={{
            display: "flex",
            justifyContent: "flex-end",
            marginBottom: "30px"
          }}>
          <div className={question}>{item}</div>
        </div>
      )
    })
  }
  function clear() {
    setData(["请输入问题"])
    chrome.storage.local.clear(function () {
      console.log("同步存储区域的数据已被清除")
    })
  }
  function SSOLogin() {
    chrome.runtime.sendMessage({
      type: "SSOLogin"
    })
  }
  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        padding: 16,
        background: "#f6f6f6",
        height: "calc(100vh - 80px)"
      }}>
      <div
        style={{
          position: "absolute",
          right: "left",
          top: "20px",
          color: "red"
        }}
        onClick={SSOLogin}>
        SSO登录
      </div>
      <div
        style={{
          position: "absolute",
          right: "20px",
          top: "20px",
          color: "red"
        }}
        onClick={clear}>
        清除历史
      </div>
      <h2 className={color}>欢迎使用AI智能助手</h2>
      <div ref={content} className={contentBox}>
        {getContent()}
      </div>
      <div
        style={{
          position: "absolute",
          width: "calc(100% - 40px)",
          bottom: "10px",
          left: "10px"
        }}>
        <textarea
          value={inputValue}
          onChange={textareaChange}
          className={textarea}
        />
        <div className={button} onClick={submit}>
          提交
        </div>
      </div>
    </div>
  )
}

export default IndexSidePanel
